package com.example.weather.service;

import com.example.weather.dto.WeatherResponse;
import com.example.weather.po.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class RedisService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private CityServiceClient cityServiceClient;
    @Autowired
    private RedisTemplate redisTemplate;

    public void cacheWeatherData(){
        //拿着所有城市id，去天聚数行  查询他们的天气数据，然后去缓存到redis数据库
        List<City> cityList = cityServiceClient.getAllCities();
        for(City c:cityList){
            WeatherResponse weatherResponse = restTemplate.getForObject("https://apis.tianapi.com/tianqi/index?" +
                    "key=58147479384231dc837ee5fd1288e6f2&city="+c.getCode()+"&type=7",WeatherResponse.class);

            //缓存到redis数据库
            redisTemplate.opsForHash().put("weatherdata",c.getCode(),weatherResponse);

        }
    }

}
